package middleware

import (
	"babyplan/service/jwt"
	"babyplan/session"
	"strings"

	"github.com/gin-gonic/gin"
)

/*
'Authorization Bearer {JwtToken}'
*/
func JwtAuth(c *gin.Context) {
	authHeader := c.Request.Header.Get("Authorization")
	tokenString := strings.TrimPrefix(authHeader, "Bearer ")
	s := session.Instance().GetSessionByToken(tokenString)
	if s != nil {
		c.Set("session", s)
		return
	}
	if claims, err := jwt.ValidateToken(tokenString); err == nil {
		s := session.Instance().CreateSession(tokenString, claims)
		c.Set("session", s)
	} else {
		c.Status(401)
		c.Abort()
	}
}
